package net.starwifi.duobao.web.dMember;

import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.mvc.*;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.IpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by ruoo on 16/1/10.
 */
@Controller("wapDMemberChargeController")
@RequestMapping("/dMember")
public class DMemberChargeController extends BaseController {

    @Autowired
    MemberService memberService;

    @Autowired
    PaymentService paymentService;

    @Autowired
    PluginService pluginService;

    @Autowired
    TradeRecordService tradeRecordService;
    @Autowired
    SettingService settingService;


    /**
     * 用户充值记录
     */
    @RequestMapping(value = "/chargeRecord", method = RequestMethod.GET)
    public String db(Model model) {
        Member member = memberService.getCurrent();
        model.addAttribute("member", memberService.getCurrent());
        List<Order> orderBy = new ArrayList<Order>();
        orderBy.add(Order.desc("id"));
        model.addAttribute("recordList", tradeRecordService.getListData(0,10,"o.memberId=?1", new Object[]{member.getId()}, orderBy));
        return "/dMember/charge_record";
    }

    @RequestMapping(value = "/chargeRecordContent", method = RequestMethod.GET)
    public String chargeRecordContent(Model model, int pageNum) {
        Member member = memberService.getCurrent();
        PageView pageView = new PageView(pageNum, 10);
        pageView.addOrder(net.starwifi.duobao.mvc.Order.desc("id"));
        pageView.addFilter(Filter.eq("memberId", member.getId()));
        Page<TradeRecord> page = tradeRecordService.getScrollData(pageView);
        model.addAttribute("recordList",page.getContent());
        return "/dMember/chargeRecord_content";
    }


    /**
     * 用户充值
     */
    @RequestMapping(value = "/recharge", method = RequestMethod.GET)
    public String recharge(Model model) {
        model.addAttribute("member", memberService.getCurrent());
        return "/dMember/recharge";
    }


    /**
     * 获取支付签名信息
     */
    @RequestMapping(value = "/rechargeSubmit")
    @ResponseBody
    public Object submit(String paymentPluginId, BigDecimal amount, HttpServletRequest request, HttpServletResponse response) {
        Member member = memberService.getCurrent();
        if (member == null) {
            return Message.error("用户不存在");
        }
        if (!member.getIsEnabled()) {
            return Message.error("账户已禁用，请联系客服");
        }
        if (amount == null || amount.compareTo(new BigDecimal(0)) <= 0) {
            return Message.error("金额非法");
        }
        if (amount.floatValue() % 1f != 0) {
            return Message.error("金额必须为整数");
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }
        String sn = AppInitListener.idGenerate.getID().toString();
        if (paymentPluginId.equals("wo3DirectPlugin")) {
            Setting BbOff = settingService.findByCode("BbOff");
            if (BbOff.getConfigValue().equals("1")) {
                return Message.error("亲爱的用户：宝币系统正在升级中，暂时无法充值，升级期间，宝币消费仍然能够继续使用！");
            }
        }
        Payment payment = new Payment();
        payment.setSn(sn); //支付流水号码
        payment.setType(Payment.Type.recharge);
        payment.setMethod(Payment.Method.online);
        payment.setStatus(Payment.Status.wait);
        payment.setPaymentMethod(paymentPlugin.getPaymentName() + Payment.PAYMENT_METHOD_SEPARATOR + paymentPlugin.getPaymentName());
        payment.setFee(BigDecimal.ZERO);
        payment.setAmount(amount);
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout()) : null);
        //payment.setFlag(0);
        payment.setPaymentPluginId(paymentPluginId);
        payment.setMemberId(member.getId());
        payment.setOrderSn(sn);
        paymentService.save(payment);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("requestUrl", paymentPlugin.getRequestUrl());
        result.put("requestMethod", paymentPlugin.getRequestMethod());
        result.put("requestCharset", paymentPlugin.getRequestCharset());
        String desc = "宝币充值";
        result.put("parameterMap", paymentPlugin.getParameterMap(payment, desc, request));
        if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
            response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
        }
        result.put("type", "success");
        return result;
    }


}
